// pages/actDetail/actDetail.js
// 引入SDK核心类
var QQMapWX = require('../../libs/qqMap.js');


import utils from '../../utils/util.js';
import {
  http
} from '../../utils/network.js'
import {
  PATHS_ALIAS,
  OTHER_INFO
} from '../../utils/api.js'


let leftTimer = '';
let leftTimerMore = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkLogin: '', //登录信息是否齐全
    fromPage:'',      //登录成功回调的页面
    loginAgainStatus: false, //再次登录结果  true 成功    false 失败
    activityId: '', //活动ID
    token: '',
    windowWidth: '', //窗口宽度
    scrollHeight: '', //滚动盒子高度
    scrollSetTop: [], //三个模块离顶高度
    ticketBoxHeight: '', //票种信息盒子高度--方便计算展开后的定位
    scrollAtiveSection: 0, //活跃的tab   0表示没有活跃tab
    toView: 1, //控制滚动tab
    watchScroll: true, //是否监听滚动
    swiperList: [], //轮播图
    groupList: [], //未满团列表,
    groupListPageSize: '10', //参团列表每页大小
    groupListPage: '1', //参团列表页数
    moreGroupShow: false, //更多参团弹框显示
    moreGroupList: [], //更多参团列表
    groupListLength: '', //参团列表长度
    actDetail: {}, //活动信息
    groupTimeIsEnd:true,      //拼团报名时间是否已结束
    ticketList: [], //票种信息
    moreTicketShow: false, //显示更多票种信息
    sysTime: '', //服务器时间--获取详情时间
    sysTimeGroupListInit: '', //服务器时间 -- 可拼团订单初始化时间
    sysTimeGroupListMore: '', //服务器时间 -- 可拼团订单更多-时间
    buyNotesShow: false, //购买须知显示
    ticketActiveInfo: {}, //选中的票种数据
    afterLoginEvent: '', //登录成功后，要执行的事件     goGroup参团
    groupActiveId: '', //选中的团的id
    ticketActiveId: '', //选中的票种id，开团用
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this;
    // 检查登录信息
    let checkLogin = this.selectComponent('#loginCheck').checkLogin();
    this.setData({
      activityId: options.id,
      // activityId:776,
      checkLogin,
      token: wx.getStorageSync('accessToken')
    });

    // 计算容器高度
    wx.getSystemInfo({
      success: function(res) {
        let windowHeight = res.windowHeight;
        let windowWidth = res.windowWidth;
        _this.setData({
          scrollHeight: windowHeight - (windowWidth / 750) * 0 + 'px',
          windowWidth: windowWidth
        })
      }
    });

  },
  onShow: function() {
    this.goTop();
    this.getActDetail();
    this.getGroupList('init');
  },
  onHide: function() {
    clearInterval(leftTimer);
    wx.hideLoading();
  },
  // 获取活动详情
  getActDetail: function() {
    let _this = this;
    let params = {
      activityId: this.data.activityId
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_ACT_DETAIL,
      params: params,
      success: function(res) {
        // //console.log(res)
        let swiperList = res.response.groupActDetail.activityPicDetail ? res.response.groupActDetail.activityPicDetail.split(',') : [];
        let ticketList = res.response.groupActTicket;
        let actDetail = res.response.groupActDetail;
        let sysTime = res.systemDate;
        // 判断拼团报名时间是否结束
        let groupTimeIsEnd = _this.data.groupTimeIsEnd;
        if (utils.timeToTimestamp(actDetail.groupEndTime) > utils.timeToTimestamp(sysTime)){
          groupTimeIsEnd = false;
        };
        _this.setData({
          sysTime: res.systemDate,
          actDetail,
          sysTime,
          groupTimeIsEnd,
          swiperList,
          ticketList,
        });
        _this.filterTicketTime(ticketList);
        // 获取三个节点离顶部距离
        setTimeout(function() {
          _this.getDemoTop();
        }, 1000);
      },
      fail(err) {
        wx.showToast({
          title: err.msg,
          icon: 'none'
        });
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    });
  },
  // 获取可拼团订单  type  init(初始化)  more(更多)
  getGroupList: function(type) {
    let _this = this;
    let params = {
      activityId: this.data.activityId, //	活动ID	string	必填
      page: type == 'init' ? 1 : this.data.groupListPage, //		页数	string	非必填
      pageSize: type == 'init' ? 3 : this.data.groupListPageSize, //		每页大小	string	非必填
    };
    http({
      path: PATHS_ALIAS.GET_GROUP_ORDER_LIST,
      params: params,
      success: function(res) {
        //console.log(res);
        let groupListLength = res.response.rows;
        // 初始化列表
        if (type == 'init') {
          let groupList = res.response.groupOrderList;
          let sysTimeGroupListInit = res.systemDate;
          _this.setData({
            groupList,
            sysTimeGroupListInit,
            groupListLength
          });
          // 参团倒计时
          _this.leftTimeRun();
        } else { //查看更多
          let moreGroupList = moreGroupList;
          let sysTimeGroupListMore = res.systemDate;
          _this.setData({
            moreGroupList: res.response.groupOrderList,
            moreGroupShow: true,
            sysTimeGroupListMore,
            groupListLength
          });
          //更多参团倒计时----在查看更多拼团时调用
          _this.leftTimeRunMore();
        }
      },
      fail: function(err) {
        //console.log(err);
      }
    })
  },
  // 计算票种报名时间及状态
  filterTicketTime(arr) {
    if (!arr || arr.length == 0) {
      return
    };
    let _this = this;
    let ticketList = arr;
    let actDetail = this.data.actDetail;
    ticketList.forEach(function(item, index) {
      if (item.entryNumFull == 'N' && item.entryStatus == 'N' && actDetail.ticketCalendar == 'Y') { //有日历，计算最早报名时间
        let nearestBookDay = item.nearestBookTime.slice(0, 10);
        if (nearestBookDay) {
          let today, nearDay, timeInterval;
          today = utils.formatTime(new Date()).slice(0, 10);
          nearDay = nearestBookDay.replace(/-/g, '/');
          timeInterval = new Date(nearDay) - new Date(today);
          if (timeInterval == 0) {
            ticketList[index].ticketStatusTxt = '最早可预订今天';
          } else if (timeInterval == 24 * 60 * 60 * 1000) {
            ticketList[index].ticketStatusTxt = '最早可预订明天';
          } else {
            nearDay = new Date(nearDay);
            ticketList[index].ticketStatusTxt = "最早可订" + (nearDay.getMonth() + 1) + "月" + nearDay.getDate() + "日";
          }
        };
        ticketList[index].ticketStatus = 'filterTime' //票种状态  filterTime（最早报名时间） full（名额已满） end(报名结束)  before(拼团未开始)
      } else if (item.entryNumFull == 'Y') { //票种名额已满
        ticketList[index].ticketStatus = 'full'
        ticketList[index].ticketStatusTxt = ''
      } else if (item.entryNumFull == 'N' && item.entryStatus == 'group_before') { //拼团未开始
        ticketList[index].ticketStatus = 'before'
        ticketList[index].ticketStatusTxt = ''
      } else if (item.entryNumFull == 'N' && (item.entryStatus == 'end' || item.entryStatus == 'group_end')) { //票种报名时间已结束
        ticketList[index].ticketStatus = 'end'
        ticketList[index].ticketStatusTxt = ''
      } else {} //没有票种日历不展示   
    });
    this.setData({
      ticketList
    })
  },
  // 参团
  goGroup: function(e) {
    //console.log(e);
    let id = e.currentTarget.dataset.id;
    let loginAgainStatus = this.data.loginAgainStatus;
    if (!loginAgainStatus) {
      this.setData({
        afterLoginEvent: 'goGroup',
        groupActiveId: id
      })
    } else {
      wx.navigateTo({
        url: '/pages/groupBuy/groupBuy?groupId=' + id,
      })
    }
  },
  // 开团
  beginGroup: function(e) {
    let ticketId = e.currentTarget.dataset.id;
    let activityId = this.data.activityId;
    let loginAgainStatus = this.data.loginAgainStatus;
    if (!loginAgainStatus) {
      this.setData({
        afterLoginEvent: 'beginGroup',
        ticketActiveId: ticketId
      })
    } else {
      wx.navigateTo({
        url: '/pages/submitOrder/submitOrder?ticketId=' + ticketId + '&activityId=' + activityId
      })
    }
  },
  // 登录-获取token
  goLogin: function() {
    this.selectComponent('#loginCheck').loginAgain();
  },
  // 查看其它票种
  moreTicketShow: function() {
    let _this = this;
    this.setData({
      moreTicketShow: true
    });

    var query = wx.createSelectorQuery() //创建节点查询器 query
    query.selectAll('#sec02').boundingClientRect() //这段代码的意思是选择Id= the - id的节点，获取节点位置信息的查询请求
    query.exec(function(res) {
      let scrollSetTop = _this.data.scrollSetTop;
      let boxHeight = res["0"]["0"].height;
      let ticketBoxHeight = _this.data.ticketBoxHeight;
      //console.log(scrollSetTop, boxHeight);
      scrollSetTop[2] = scrollSetTop[2] + (boxHeight - ticketBoxHeight);
      _this.setData({
        scrollSetTop,
        ticketBoxHeight: boxHeight
      });
    });

  },
  // 登录成功--回调
  // loginSuccess: function (e) {
  //   // console.log(e);
  //   let afterLoginEvent = this.data.afterLoginEvent;
  //   let groupActiveId = this.data.groupActiveId;
  //   let ticketActiveId = this.data.ticketActiveId;
  //   let activityId = this.data.activityId;

  //   if (e.detail.status == '0') {
  //     this.setData({
  //       token: wx.getStorageSync('accessToken'),
  //       checkLogin:true
  //     });
  //     switch (afterLoginEvent){
  //       case 'goGroup':   //参团
  //         wx.navigateTo({
  //           url: '/pages/groupBuy/groupBuy?groupId=' + groupActiveId
  //         })
  //         break;
  //       case 'beginGroup':   //开团
  //         wx.navigateTo({
  //           url: '/pages/submitOrder/submitOrder?ticketId=' + ticketActiveId + '&activityId=' + activityId
  //         })
  //         break;

  //     }
  //   }
  // },
  // 再次登录--及回调控制  type: beginGroup开团  goGroup参团
  loginThird: utils.throttle(function(e) {
    // console.log(e);
    let _this = this;
    let type = e.currentTarget.dataset.type;
    let fromPage = '';  
    let checkLogin = this.data.checkLogin; //登录信息是否存在
    let activityId = this.data.activityId;
    switch (type) {
      case 'beginGroup':
        fromPage = `/pages/submitOrder/submitOrder?ticketId=${e.currentTarget.dataset.id}&activityId=${activityId}`
        break;
      case 'goGroup':
        fromPage = `/pages/groupBuy/groupBuy?groupId=${e.currentTarget.dataset.id}`
        break;
    };
    this.setData({
      fromPage: encodeURIComponent(fromPage)
    });

    if (checkLogin) { //重新登录
      wx.showLoading({
        title: '加载中...',
        mask:true
      });
      let params = {
        logType: '07',
        thirdId: wx.getStorageSync('unionId'),
        resId: 'weixin',
        userSystem: '0052'
      };
      http({
        path: PATHS_ALIAS.THIRD_USER_LOGIN,
        params: params,
        header: {
          sendChl: 'hzsmk.h5', // 应用渠道(必填) 
          sendClient: 'hellohzsmk', //应用验证码(必填) string 
          clientCode: OTHER_INFO.clientCode
        },
        success: function(res) {
          //console.log(res);
          wx.setStorageSync('accessToken', res.response.accessToken);
          wx.setStorageSync('userId', res.response.userId);
          wx.setStorageSync('mobile', res.response.mobile);
          _this.setData({
            loginAgainStatus: true,
            checkLogin:true
          });
          switch (type) {
            case 'beginGroup':
              _this.beginGroup(e);
              break;
            case 'goGroup':
              _this.goGroup(e);
              break;
          }
        },
        fail: function(err) {
          //console.log(err);
          _this.setData({
            loginAgainStatus: false
          });
          if (err.code == 'PY0005') { //跳转输入手机号登录
            wx.navigateTo({
              url: `/pages/phoneLogin/phoneLogin?fromPage=${_this.data.fromPage}`,
            })
          }
        },
        complete: function() {

        }
      })
    } else {
      this.goLogin();
    }
  }),
  // 滚动事件
  scroll: function(e) {
    if (!this.data.watchScroll) {
      return;
    };
    let _this = this;
    // //console.log(e.detail.scrollTop);
    let scrollTop = e.detail.scrollTop;
    let windowWidth = this.data.windowWidth;
    if (scrollTop < this.data.scrollSetTop[0] - (windowWidth / 750) * 80) {
      _this.setData({
        scrollAtiveSection: 0
      });
    } else if (scrollTop > this.data.scrollSetTop[2] - (windowWidth / 750) * 80) {
      _this.setData({
        scrollAtiveSection: 3
      });
    } else if (scrollTop > this.data.scrollSetTop[1] - (windowWidth / 750) * 80) {
      _this.setData({
        scrollAtiveSection: 2
      });
    } else if (scrollTop > this.data.scrollSetTop[0] - (windowWidth / 750) * 80) {
      _this.setData({
        scrollAtiveSection: 1
      });
    }
  },
  // 点击顶部tab,跳转
  goTab: function(e) {
    let _this = this;
    let windowWidth = this.data.windowWidth;
    let i = e.currentTarget.dataset.id;
    let top = this.data.scrollSetTop[i - 1] - (windowWidth / 750) * 80;
    this.setData({
      watchScroll: false,
      toView: top,
      scrollAtiveSection: i
    });
    setTimeout(function() {
      _this.setData({
        watchScroll: true
      });
    }, 500)
  },
  // 拨打电话
  telShopPhone(e) {
    wx.makePhoneCall({
      phoneNumber: e.target.dataset.phone,
    })
  },
  // 回到顶部
  goTop: function() {
    let _this = this;
    this.setData({
      watchScroll: false,
      toView: 0,
      scrollAtiveSection: 0
    });
    setTimeout(function() {
      _this.setData({
        watchScroll: true
      });
    }, 50)
  },
  // 查看更多参团--按钮
  getMoreGroup: function() {
    clearInterval(leftTimerMore);
    this.getGroupList('more');
  },
  // 更多参团--换一批
  moreGroupChange: function() {
    //console.log('更多参团--换一批');
  },
  // 更多参团弹框-关闭
  moreGroupHide: function() {
    this.setData({
      moreGroupShow: false
    });
  },
  // 购买须知弹框显示
  buyNotesShow: function(e) {
    //console.log(e);
    this.setData({
      buyNotesShow: true,
      ticketActiveInfo: e.currentTarget.dataset.data
    })
  },
  // 购买须知弹框关闭
  closeBuyNotes: function(e) {
    // //console.log(e)
    this.setData({
      buyNotesShow: false
    })
  },
  // 打开地图
  jumpMap: function(e) {
    // //console.log(e.currentTarget.dataset.address)
    // 实例化API核心类
    var demo = new QQMapWX({
      key: 'XQ4BZ-3GEWJ-MNMFA-F3BGL-A6C3Z-X6BIP' // 必填
    });
    // 调用接口
    demo.geocoder({
      address: e.currentTarget.dataset.address,
      success: function(res) {
        //console.log(res);
        let latitude = res.result.location.lat;
        let longitude = res.result.location.lng;
        wx.openLocation({
          latitude,
          longitude,
          name: res.result.title,
          // address: '这是地址描述这是地址描述这是地址描述这是地址',
          scale: 18
        })
      },
      fail: function(res) {
        // //console.log(res);
        // 地址错误时，默认地址为近江时代大厦
        let latitude = 39.903229;
        let longitude = 116.39772;
        wx.openLocation({
          latitude,
          longitude,
          name: '地址定位出错，请联系商家',
          address: '地址定位出错，请联系商家',
          scale: 18
        })
      },
      complete: function(res) {
        // //console.log(res);
      }
    });
  },

  // 获取三个节点离顶部距离 方便监听滚动
  getDemoTop: function() {
    var _this = this;
    var query = wx.createSelectorQuery() //创建节点查询器 query
    query.selectAll('.scroll_sec').boundingClientRect() //这段代码的意思是选择Id= the - id的节点，获取节点位置信息的查询请求
    query.exec(function(res) {
      //console.log(res);
      let scrollSetTop = [];
      let ticketBoxHeight = '';
      res[0].forEach(function(item, index) {
        scrollSetTop.push(item.top);
        if (index == 1) {
          ticketBoxHeight = item.height;
        }
      });
      _this.setData({
        scrollSetTop: scrollSetTop,
        ticketBoxHeight
      })
    });
  },
  // 参团倒计时
  leftTimeRun: function() {
    let _this = this;
    _this.leftTimeRunFilter();

    leftTimer = setInterval(function() {
      _this.leftTimeRunFilter();
    }, 1000)
  },
  // 参团倒计时--计算时间
  leftTimeRunFilter: function() {
    let _this = this;
    let groupList = _this.data.groupList;
    let sysTimeGroupListInit = _this.data.sysTimeGroupListInit;
    if (!groupList || groupList.length == 0) {
      return;
    }
    groupList.forEach(function(item, index) {
      if (item.timeLeft || item.timeLeft ==0) { //判断TimeLeft 是否存在  注意0属于存在
        groupList[index].timeLeft = item.timeLeft;
      } else {
        groupList[index].timeLeft = utils.timeToTimestamp(item.tradeTime) + item.groupBuyDeadLine * 60 * 60 * 1000 - utils.timeToTimestamp(sysTimeGroupListInit);
      };
      if (groupList[index].timeLeft > 0) {
        groupList[index].timeLeft = groupList[index].timeLeft - 1000;
      } else {
        groupList[index].timeLeft = 0;
      }
    });
    _this.setData({
      groupList: groupList
    });
  },
  // 更多参团倒计时
  leftTimeRunMore: function() {
    let _this = this;
    this.leftTimeRunMoreFilter();
    leftTimerMore = setInterval(function() {
      _this.leftTimeRunMoreFilter();
    }, 1000)
  },
  // 更多参团倒计时--计算时间
  leftTimeRunMoreFilter: function() {
    let _this = this;
    let moreGroupList = _this.data.moreGroupList;
    let sysTimeGroupListMore = this.data.sysTimeGroupListMore;
    if (!moreGroupList || moreGroupList.length == 0) {
      return;
    }
    moreGroupList.forEach(function(item, index) {
      if (item.timeLeft) {
        moreGroupList[index].timeLeft = item.timeLeft;
      } else {
        moreGroupList[index].timeLeft = utils.timeToTimestamp(item.tradeTime) + item.groupBuyDeadLine * 60 * 60 * 1000 - utils.timeToTimestamp(sysTimeGroupListMore);
      };
      if (moreGroupList[index].timeLeft > 0) {
        moreGroupList[index].timeLeft = moreGroupList[index].timeLeft - 1000;
      }
    });
    _this.setData({
      moreGroupList: moreGroupList
    });
  },
  // 阻止事件冒泡--空事件
  stopDefault: function() {},


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})